<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div style="margin-top: 20px;padding-bottom: 10px">
        <div style="font-size: 35px;font-family: SimSun">封&nbsp;条</div>
      </div>
      <div class="delivery-agency-div" :class="{ 'official-seal-display': isDisplay }">
        <img class="official-seal" src="../../assets/tupian.png" alt="Image">
        <div>
          <span @click="editlabel('时间', 'YYYYMMDD1')">
            <span class="vertical-div" v-if="form.date">{{ form.date }}</span>
            <span class="vertical-div" v-else>年<br><br>月<br><br>日</span>
          </span>
        </div>
        <div class="seal-content">
          朔<br>州<br>经<br>济<br>开<br>发<br>区<br>管<br>理<br>委<br>员<br>会<br><br>封
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="参数输入" width="30%" align-center>
    时间：<el-date-picker v-model="date1" value-format="YYYY-MM-DD" type="date" style="width: 60%" clearable />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="toCapitalLetters()">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      form: {},
      isPdfExport: false, // 控制打印样式
      isDisplay: true, // 控制官方印章的显示
      status: '', //当前文书的状态
      date1: "",
      dialogVisible: false,
      paramName: "",
      paramtype: "",
      paramContent: "",
    }
  },
  created() {
    window.parent.getTemplateData((data, status) => {
      this.form = data;
      this.status = status;
    })
    window.postForm = () => {
      this.postForm();
    }
  },

  mounted() {
    window.parent.changeTemplateDow();
  },

  methods: {
    // 导出为pdf
    exportPDF() {
      if (this.status !== '4') {
        this.isDisplay = false
      }
      this.savePDF()
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `封条.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                this.isDisplay = true;
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            this.isDisplay = true;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '封条.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },
    toCapitalLetters() {
      if (this.date1 == null) {
        this.form.date = ''
        this.dialogVisible = false
        return
      }
      // 按-分割字符串
      let year = this.date1.split('-')[0];
      let month = this.date1.split('-')[1];
      let day = this.date1.split('-')[2];

      // 定义数字映射表
      let numberMap = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];

      // 转换年份（逐位替换）
      year = year.replace(/\d/g, match => numberMap[parseInt(match)]);

      // 转换月份（特殊处理10-19）
      if (month === '10') {
        month = '十';
      } else if (month.startsWith('1') && month.length === 2) {
        month = '十' + numberMap[parseInt(month.charAt(1))];
      } else {
        month = month.replace(/\d/g, match => numberMap[parseInt(match)]);
        // 月若是〇开头，转换后去掉〇
        if (month.charAt(0) === '〇') {
          month = month.slice(1);
        }
      }

      // 转换日（特殊处理10-19和20、30）
      if (day === '10') {
        day = '十';
      } else if (day === '20') {
        day = '二十';
      } else if (day === '30') {
        day = '三十';
      } else if (day.startsWith('1') && day.length === 2) {
        day = '十' + numberMap[parseInt(day.charAt(1))];
      } else if (day.startsWith('2') && day.length === 2) {
        day = '二十' + numberMap[parseInt(day.charAt(1))];
      } else if (day.startsWith('3') && day.length === 2) {
        day = '三十' + numberMap[parseInt(day.charAt(1))];
      } else {
        day = day.replace(/\d/g, match => numberMap[parseInt(match)]);
        // 日若是〇开头，转换后去掉〇
        if (day.charAt(0) === '〇') {
          day = day.slice(1);
        }
      }


      // 赋值
      this.form.date = year + '年' + month + '月' + day + '日';

      this.dialogVisible = false
    },
    editlabel(val, type) {
      this.paramName = val;
      this.paramtype = type;
      this.dialogVisible = true;
    },
  }
}
</script>

<style scoped>
:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}

/* 封条内容 */
.delivery-agency-div {
  width: 250px;
  height: 850px;
  /* 定位 */
  position: relative;
  left: 200px;
  top: -25px;
  border: 1px solid #000;
  font-family: "仿宋", serif;
  font-size: 11mm;
}

.official-seal {
  display: none;
  position: absolute;
  bottom: 200px;
  left: 28px;
  width: 4.2cm;
  height: 4.2cm;
  z-index: 30;
}

.seal-content {
  height: 750px;
  position: absolute;
  top: 80px;
  right: 5px;
}

.vertical-div {
  position: absolute;
  bottom: 50px;
  left: 80px;
  width: 40px;
  z-index: 20;
}
</style>
